#include <opencv2/core/core.hpp>
#include "opencv2/imgproc/imgproc.hpp"
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/ml/ml.hpp>

#include <iostream>
#include <fstream>
#include <vector>
#include "preprocesamiento.h"
#include "Placa.h"
#include "DetectorRegiones.h"
#include "OCR.h"
#include "mainANPR.h"
#include "Pruebas.h"

using namespace std;
using namespace cv;
DetectorRegiones detector;    
int min_threshold = 50;
int max_trackbar = 150;
int max_thresh = 255;
int max_lineLength = 110;
int deltaThresholdCannyLow = 15;//max_thresh;
int deltaThresholdCannyHigh = 140;//max_thresh;
const char* probabilistic_name = "Hough";
const char* canny_name = "Canny";

void houghRun(int,void*){
	detector.run(false);
}

int mainVideo (string videoName)
{
	cout << "OpenCV Automatic Number Placa Recognition\n";
	string filename = "nombre";
	Mat input_image;
	detector.houghWindowName = _strdup(probabilistic_name);
	detector.cannyWindowName = _strdup(canny_name);
	detector.deltaThresholdHough = 35;//max_trackbar;
	detector.deltaThresholdCannyLow = 15;//max_thresh;
	detector.deltaThresholdCannyHigh = 140;//max_thresh;
	detector.lineLength = 40;
	detector.deltaTiempo = 0;
	VideoCapture cap;
	Vector<Mat> writerFrames;


	cap.open(videoName);
	if( cap.isOpened() ){
		cout << "Video " << filename <<
			": width=" << cap.get(CV_CAP_PROP_FRAME_WIDTH) <<
			", height=" << cap.get(CV_CAP_PROP_FRAME_HEIGHT) <<
			", nframes=" << cap.get(CV_CAP_PROP_FRAME_COUNT) <<
			", fps=" << cap.get(CV_CAP_PROP_FPS) <<
			", encode=" << cap.get(CV_CAP_PROP_FOURCC) << endl;
		VideoWriter vw;
		vw.open("video_result_x.avi",CV_FOURCC('F','M','P','4'),cap.get(CV_CAP_PROP_FPS),Size(cap.get(CV_CAP_PROP_FRAME_WIDTH) ,cap.get(CV_CAP_PROP_FRAME_HEIGHT)));
		detector.writer = vw;
	}

	if( !cap.isOpened() )
	{
		cout << "Could not initialize capturing...\n";
		return -1;
	}
	int h=-1;
	for(;;)
	{
		cout << "Processing frame: " << ++h << endl ;
		char nombreFrame[30];
		sprintf(nombreFrame,"framesTest/frame%d.jpg",h);
		Mat frame;
		cap >> frame;
		if( frame.empty() )
			break;
		cvtColor(frame, input_image , CV_BGR2GRAY);
		detector.input_image_color = frame.clone();
		preprocesar(input_image,input_image,15,140);
		detector.processedImage = input_image;
		Mat resultado;
		if (h%2)
			resultado = detector.dibujarCorners(); 
		else 
			resultado = detector.run(true);  
		detector.writer.write(resultado);
		if (detector.detectado)
			imwrite(nombreFrame,frame);
		//writerFrames.push_back(resultado);
	}
	/*
	for (size_t i = 0; i < writerFrames.size(); i++){
	detector.writer.write(writerFrames[i]);
	}
	*/
	//detector.run(true);
	cout << detector.deltaTiempo*1./getTickFrequency();
	return 0;
}


int mainImagen (string filename)
{
	cout << "OpenCV Automatic Number Placa Recognition\n";
	Mat input_image;
	//Detect posibles placa regions
	detector.nombreArchivo = filename;
	detector.houghWindowName = _strdup(probabilistic_name);
	detector.cannyWindowName = _strdup(canny_name);
	detector.deltaThresholdHough = 35;//max_trackbar;
	detector.lineLength = 40;
	detector.deltaTiempo = 0;
	detector.input_image_color = imread(filename,CV_LOAD_IMAGE_COLOR);
	Mat img = imread(filename,CV_LOAD_IMAGE_GRAYSCALE);
	Mat imgPreprocesada;
	preprocesarPasoaPaso(img,imgPreprocesada,deltaThresholdCannyLow,deltaThresholdCannyHigh,5);
	detector.processedImage = imgPreprocesada;

	//namedWindow( probabilistic_name, WINDOW_AUTOSIZE );
	//namedWindow( canny_name, WINDOW_AUTOSIZE );
	detector.run(false);
	OCR ocrModule;
	ocrModule.init();
	ocrModule.reconocerPlaca(detector.input_image_color,*(detector.cornersGlobal));
	return 0;
}


int cannyThresh1 = 50;
int cannyThresh2 = 140;
Mat imagenColor;
Mat imagenGris;
Mat resultado;
void enhance (int,void*){
	//preprocesar(imagenGris,resultado,cannyThresh1,cannyThresh2);
	preprocesarPlaca(imagenGris,resultado,cannyThresh1);
	imshow("CannyWindow",resultado);
}
int enhancementTest(String nombreArchivo){

	imagenColor = imread(nombreArchivo,CV_LOAD_IMAGE_COLOR);
	imagenGris = imread(nombreArchivo,CV_LOAD_IMAGE_GRAYSCALE);
	namedWindow( "Original", WINDOW_AUTOSIZE );
	namedWindow( "CannyWindow", WINDOW_AUTOSIZE );
	createTrackbar( "CannyLow", "CannyWindow", &cannyThresh1, max_thresh, enhance);
	createTrackbar( "CannyHigh", "CannyWindow", &cannyThresh2, max_thresh*2, enhance);
	imshow("Original",imagenGris);
	enhance(0,0);
	return 0;
}


int mainANPR(String nombreImagen){
	/*
	detector.resultadosPreproc.open ("resultPreproc.txt");
	detector.resultadosContorno.open ("resultContorno.txt");
	detector.resultadosHough.open ("resultHough.txt");
	*/
	//enhancementTest("3.jpg");
	//mainVideo(nombreImagen);
	//mainVideo(nombreImagen);
	//Pruebas prueba;
	//prueba.probarCanny();
	/*
	detector.resultadosPreproc.close();
	detector.resultadosContorno.close();
	detector.resultadosHough.close();
	*/
	return 0;
}